using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using UnityEngine;
using System.Threading.Tasks;

public class ExecAsyncUtil : MonoBehaviour
{
    /// <summary>
    /// Run the specified exec, argument, ignoreError and output.
    /// </summary>
    /// <param name="exec">Exec.</param>
    /// <param name="argument">Argument.</param>
    /// <param name="ignoreError">treat error log as normal log</param>
    /// <param name="output">all normal log and error log</param>
    /// 
    public static async Task<int> RunAsync(string exec, string argument, string workingDir = null)
    {
        var p = new System.Diagnostics.Process();
        p.StartInfo.FileName = exec;
        p.StartInfo.Arguments = argument;
        UnityEngine.Debug.Log("execute:  " + exec + " " + argument);
        p.StartInfo.UseShellExecute = false;
        p.StartInfo.RedirectStandardError = true;
        p.StartInfo.RedirectStandardInput = true;
        p.StartInfo.RedirectStandardOutput = true;
        p.StartInfo.CreateNoWindow = true;
        if (workingDir != null)
        {
            p.StartInfo.WorkingDirectory = workingDir;
        }

        p.OutputDataReceived += (object sender, DataReceivedEventArgs e) =>
        {
            if (e.Data == null) return;
            // print log
            UnityEngine.Debug.Log(e.Data);

        };
        p.ErrorDataReceived += (object sender, DataReceivedEventArgs e) =>
        {
            if (e.Data == null) return;
            // print log
            UnityEngine.Debug.LogError(e.Data);

        };
        p.Start();


        p.BeginOutputReadLine();
        p.BeginErrorReadLine();

        while(!p.HasExited)
        {
            await Task.Delay(100);
        }

        return p.ExitCode;

    }
}
